<template>
  <div class="loginbox">
    <el-row>
      <el-col :span="24" class="login">
        <h4 style="margin-top: 0;" v-if="isPsw == 0">账号登录</h4>
        <h4 style="margin-top: 0;" v-else-if="isPsw == 1">手机验证码登录</h4>
        <h4 style="margin-top: 0;" v-else-if="isPsw">绑定手机号</h4>
        <el-form v-if="isPsw ==0" ref="form" :model="form" :rules="rules" label-width="80px">
          
          <el-form-item  label="账号:" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="psw">
            <el-input type="password" v-model="form.psw"></el-input>
          </el-form-item>
        </el-form>
        <el-form  v-else ref="form2" :model="form2" :rules="rules2" label-width="80px">
          <el-form-item label="手机:" prop="tel">
            <el-input v-model="form2.tel"></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="numer" style="text-align:left;">
            <el-input  v-model="form2.numer" style="width:160px"></el-input>
            <el-button type="primary" @click="reverTime(22)" v-if="isPsw == 2" :disabled="disabled" style="margin-left:19px">{{timeValue}}</el-button>
            <el-button type="primary" @click="reverTime(23)" v-else :disabled="disabled" style="margin-left:19px">{{timeValue}}</el-button>
          </el-form-item>
        </el-form>
        <div style="padding-left:40px;font-size:14px">
          <el-row v-show="isPsw == 0">
            <el-col :span="12">
              <div style="text-align:left" ><el-checkbox v-model="checked" class="bule">记住密码</el-checkbox></div>
            </el-col>
            <el-col :span="12">
              <!-- <div style="text-align:right" class="bule">忘记密码</div> -->
            </el-col>
          </el-row>

          <el-button type="primary" style="width:100%;margin:10px 0;" v-if="isPsw ==2" @click="passLogin">确认</el-button>
          <el-button type="primary" style="width:100%;margin:10px 0;" v-else @click="goHome">登录</el-button>
          <el-row v-if="isPsw != 2">
            <el-col :span="12">
              <div style="text-align:left" >没账号？<router-link to="register" class="bule">去注册</router-link></div>
            </el-col>
            <el-col :span="12">
              <div style="text-align:right" v-if="isPsw == 0" class="bule" @click="checkLogin(1)">手机验证码登录</div>
              <div style="text-align:right" v-else class="bule" @click="checkLogin(0)">账号密码登录</div>
            </el-col>
          </el-row>
          
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import crypto from 'crypto'
import Http from '@/Http/Http'
import {mapActions,mapGetters,mapState} from 'vuex'
export default {
  data() {
    const name = (rele,value,callback) => {
      if(value ===''){
        return callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }
    const psw = (rele,value,callback) => {
      if(value ===''){
        return callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const tel = (rele,value,callback) => {
      if(value ===''){
        return callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }
    const numer = (rele,value,callback) => {
      if(value ===''){
        return callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {    
      form: {
        name:'',
        psw:''
      },
      form2:{
        tel:'',
        numer:''
      },
      isLogin:false,
      isPsw:0,
      disabled:false,
      checked:true,
      time:60,
      timeValue:'获取验证码',
      rules2:{
        tel:[
          {validator:tel,trigger:'blur'}
        ],
        numer:[
          {validator:numer,trigger:'blur'}
        ]
      },
      rules:{
        name:[
          {validator:name,trigger:'blur'}
        ],
        psw:[
          {validator:psw,trigger:'blur'}
        ]
      }
    }
  },
  
  created(){
   
  },
  mounted(){
    this.getCookie()
  },
  methods:{
    ...mapActions(['isAuth']),
    goHome() {
      this.isPsw == 0? this.pswLogin() : this.telLogin();
    },
    pswLogin() {
      this.$refs['form'].validate( (valid) => {
        
        if (valid) {
          this.checked ? this.setCookie (this.form.name,this.form.psw,365) : this.setCookie('','',-1);
         
          const md5 = crypto.createHash("md5");
          md5.update(this.form.psw);
          const psw = md5.digest('hex')
          Http.loginIn({
            "account_name":this.form.name,
            "password":psw
          })
          .then( res => {
            if( res.data.code == 200){
              sessionStorage.setItem('tel',res.data.data.user.tel);
              sessionStorage.setItem('hospitalAuth',res.data.data.user.token);
              sessionStorage.setItem('userName',res.data.data.hospital_name);
              sessionStorage.setItem('is_auth',res.data.data.is_auth);
              sessionStorage.setItem('userPass',this.form.name);
              this.isLogin = true;
              if(res.data.data.user.tel){
                this.$router.push('/Home/Push')
              } else {
                this.checkLogin(2)
              }
            } else {
              this.$message.error(res.data.message)
            }
          })
          .catch( error => {
            this.$message.error('服务器请求失败')
          })
        }
      })
    },
    telLogin() {
      const obj ={
        'tel':this.form2.tel,
        'vcode':this.form2.numer
      };
      Http.LoginByTel(obj)
      .then(res =>{
        
        if(res.data.code == 200) {
          sessionStorage.setItem('hospitalAuth',res.data.data.user.token);
          sessionStorage.setItem('userName',res.data.data.hospital_name);
          sessionStorage.setItem('is_auth',res.data.data.is_auth);
          sessionStorage.setItem('userPass',this.form.name);
          this.$router.push('/Home/Push');
        }else{
          this.$message.error(res.data.message)
        }
      })
    },
    passLogin() {
      if(this.isLogin){
        Http.bindTel({"tel":this.form2.tel,"vcode":this.form2.numer})
        .then(res => {
          console.log(res)
          if(res.data.code == 200){
            this.$message.success('绑定成功')
            this.$router.push('/Home/Push');
            this.isLogin = false;
          } else {

          }
        })
      }
    },
    setCookie(c_name,c_pwd,exdays) {
      const exdate = new Date() ; //获取时间
      exdate.setTime(exdate.getTime()+24*60*60*1000*exdays); //保存天数
      window.document.cookie = `userName=${c_name};path=/;expires=${exdate.toGMTString()}`;
      window.document.cookie = `userPwd=${c_pwd};path=/;expires=${exdate.toGMTString()}`;
    },
    getCookie(){
      if (document.cookie.length > 0) {
        var arr = document.cookie.split(';');
        for(let i = 0; i < arr.length; i++){
          let arr2 = arr[i].split('=');
          if (arr2[0].replace(/^\s+|\s+$/g,'') == 'userName') {
            this.form.name = arr2[1];
          } else if (arr2[0].replace(/^\s+|\s+$/g,'') == 'userPwd') {
            this.form.psw = arr2[1]
          }
        }
      }
    },
    clearCookie() {
      this.setCookie('','',-1)
    },
    checkLogin(val) {
      //this.$refs['form'].resetFields()
      this.isPsw == 0? '' : this.$refs['form2'].resetFields();
      this.isPsw = val;
    },
    reverTime(val) {
      this.disabled = true;
      if(!this.form2.tel){ 
        this.$message.error('请输入电话号码') 
        return
      }
      Http.getHmsAuthCode({
        "phone":this.form2.tel,
        "type":val
      }).then(res=>{
        if(res.code == -1002){
          this.$message.error(res.message)
        }
      });
      var intTime = setInterval(()=>{
        -- this.time;
        this.timeValue = `${this.time}s`
        if (this.time <1) {
          this.disabled = false;
          this.time = 60;
          clearInterval(intTime)
          this.timeValue = '重新发送'
        }
      },1000)
    }
  }
}
</script>
<style>
.loginbox{
  
  height: 100vh;
  background:#e5e5e5;
  display: flex;
  	justify-content: center;
  	align-items: center;
}
.login{
  width:420px !important;
  text-align:center;
  padding:40px 40px 40px 0;
  background:#fff;
  border-radius: 8px
}
.bule{
  color:#5BA8F7;
}
</style>
